#! /bin/bash


# update yum warehouse
sudo DEBIAN_FRONTEND=noninteractive apt update

# install coturn,curl,whiptail
sudo DEBIAN_FRONTEND=noninteractive apt install curl -y
sudo DEBIAN_FRONTEND=noninteractive apt install coturn -y
sudo DEBIAN_FRONTEND=noninteractive apt install whiptail -y

# grep private and public ip and servername
get_ip(){
	private_ip1=$(ip a | grep eth0 | grep inet)
	private_ip2=${private_ip1:9:18}
	private_ip=${private_ip2%%/*}
	public_ip=$(curl icanhazip.com)
}
get_ip


# create key and cert
openssl req -x509 -newkey rsa:2048 -keyout /opt/turn_key.pem -out /opt/turn_cert.pem -days 9999 -nodes \
-subj "/C=US/ST=New York/L=New York City/O=Example Company/OU=IT Department/CN=example.com"


# append some configs on the config_file
cat >> /etc/coturn/turnserver.conf <<EFO
# listening ip
listening-ip=0.0.0.0

# listening port
listening-port=3478

# turn server tls listening port 
tls-listening-port=5349

# relay ip
relay-ip=$private_ip

# public network ip
external-ip=$public_ip

# turn on password verify
lt-cred-mech

# cert and key location or route
cert=/opt/turn_cert.pem
pkey=/opt/turn_key.pem

# turn off CLI
no-cli

# set username and password
user=leading:leading123

# use port range
min-port=49152
max-port=65535

# match domain and public ip
realm=$public_ip

# server name
server-name=$servername
EFO

# restart coturn
sudo systemctl start coturn
sudo systemctl restart coturn
sudo systemctl enable coturn

# test turn and succesfull
turn_test1=$(turnutils_uclient -p 3478 -u leading -w leading123 -T $public_ip -y | grep jitter)
#exitstatus=$?
turn_test2=$(echo "$turn_test1" | cut -d':' -f3)
turn_test=${turn_test2:9:6}

if [ $turn_test = 'jitter' ]; then
	whiptail --title "Turn Server Deployment" --msgbox "turn server install seccessful!
    username:leading
    password:leading123" 10 60
else
	whiptail --title "Turn Server Deployment" --msgbox "turn server install failed,please again" 10 60
	exit 1
fi
